package com.lkd.http.controller;

import com.lkd.service.OrderService;
import com.lkd.utils.ConvertUtils;
import com.lkd.vo.PayVO;
import com.lkd.wxpay.WXConfig;
import com.lkd.wxpay.WxPayDTO;
import com.lkd.wxpay.WxPaySDKUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private WxPaySDKUtil wxPaySDKUtil;

    /**
     * 微信小程序支付
     * 存入订单数据,使用微信支付接口
     * @param payVO
     * @return
     */
    @PostMapping("/weixinPay")
    public String weixinPay(@RequestBody PayVO payVO) {
        var orderEntity = orderService.createOrder(payVO);//创建订单
        //封装支付请求对象调用支付
        var wxPayDTO = new WxPayDTO();
        wxPayDTO.setBody(orderEntity.getSkuName());//商品名称
        wxPayDTO.setOutTradeNo(orderEntity.getOrderNo());//订单编号
        wxPayDTO.setTotalFee(orderEntity.getAmount().intValue());//商品金额
        wxPayDTO.setOpenid(orderEntity.getOpenId());//openId
        //微信支付接口
        String responseData = wxPaySDKUtil.requestPay(wxPayDTO);
        return responseData;
    }

    /**
     * 微信支付回调接口
     *
     * @param request
     * @param response
     */
    @RequestMapping("/payNotify")
    @ResponseBody
    public void payNotify(HttpServletRequest request, HttpServletResponse response) {
        log.info("回调方法执行");

        try {
            ServletInputStream inputStream = request.getInputStream();
            //获取支付回调参数
            String notifyResult = ConvertUtils.convertToString(inputStream);
            //参数解析,判断是否,支付成功
            String orderSn = wxPaySDKUtil.validPay(notifyResult);

            if (StringUtils.isNotBlank(orderSn)) {
                log.info("回调成功");
                //回调成功,订单微服务,调用售货机微服务发送出货协议
                orderService.vendout(orderSn);
                //给微信支付一个成功的响应
                response.setContentType("text/xml");
                response.getWriter().write(WXConfig.RESULT);


            }

        } catch (Exception e) {

            log.error("支付回调处理失败", e);

        }


    }

}
